package com.boot.mall.cart.interceptor;

import com.boot.common.constant.AuthConstant;
import com.boot.common.constant.CartConstant;
import com.boot.common.vo.MemberResponseVo;
import com.boot.mall.cart.to.UserInfoTo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 对用户请求拦截，判断用户的登录状态，并封装传递给Controller
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 在执行目标方法之前执行，false为不放行，true为放行
     *      执行逻辑：首先判断用户是否登录，如果用户已登录，设置userInfoTo的id为用户登录的id
     *               如果用户没有登录，则随机生成一个id值
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfoTo userInfoTo = new UserInfoTo();
        // 从session中获取用户信息
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthConstant.LOGIN_USER);

        if (member != null){    //用户已登录
            userInfoTo.setUserId(member.getId().toString());
        }

        // 设置分配给用户的key值
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                if (CartConstant.TEMP_COOKIE_USER_NAME.equals(cookie.getName())){
                    userInfoTo.setUserKey(cookie.getValue());
                }
            }
        }

        // 值为空，该请求没有带key值，说明是第一次点击，随机设置一个
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            String key = UUID.randomUUID().toString();
            userInfoTo.setUserKey(key);
        }

        if (userInfoTo.getUserId() == null){
            // 用户没有登录，设置用户状态为临时用户
            userInfoTo.setIsTempUser(true);
        }
        System.out.println("用户信息：" + userInfoTo);
        threadLocal.set(userInfoTo);

        return true;
    }

    /**
     * 在方法执行之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        Cookie cookie = new Cookie(CartConstant.TEMP_COOKIE_USER_NAME,userInfoTo.getUserKey());
        cookie.setDomain("guli.com");
        cookie.setMaxAge(CartConstant.TEMP_COOKIE_USER_TIMEOUT);
        response.addCookie(cookie);
    }
}
